﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CPPEI.Console
{
    class Command
    {
        private static Dictionary<string, ICommand> s_commandDict = new Dictionary<string, ICommand>();

        public static void Register(string cmd, ICommand command)
        {
            if (!s_commandDict.ContainsKey(cmd))
            {
                s_commandDict.Add(cmd, command);
            }
        }

        public static void Run()
        {
            string cmdString = System.Console.ReadLine();
            while (!Execute(cmdString))
            {
                cmdString = System.Console.ReadLine();
            }
        }

        private static bool Execute(string cmdString)
        {
            if (string.Equals(cmdString, "Exit", StringComparison.CurrentCultureIgnoreCase))
            {
                return true;
            }

            string[] cmdStringArr = cmdString.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string key in s_commandDict.Keys)
            {
                if (string.Equals(key, cmdStringArr[0], StringComparison.CurrentCultureIgnoreCase))
                {
                    List<string> paramList = cmdStringArr.ToList();
                    if(paramList.Count > 0)
                    {
                        paramList.RemoveAt(0);
                    }
                    s_commandDict[key].Execute(key, paramList.ToArray());
                }
            }

            return false;
        }
    }
}
